﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Xml;
using System.Collections.Generic;
using System.Text;
using System.Net;

/// <summary>
/// 淘宝订单相关
/// </summary>
public class TB_Trade 
{
    public TB_Trade()
    {
    }
    #region 下载订单列表及订单详细信息

    /// <summary>
    /// 下载订单列表及订单详细信息

    /// </summary>  
    /// <returns>返回下载总条数</returns>
    public int DownTBTrade(string username, string password, string appkey, string certcode,string sessionId)
    {
        int _PageSize = 100;
        string[,] param = new string[,] { { "nick", username }, { "sip_apiname", "taobao.trades.sold.get" }, { "fields", "tid" }, {"page_size","10"},{"page_no","1"},
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
        BS2.BSTaobaoAPI.TaobaoAPI.setAPPID(appkey);
        BS2.BSTaobaoAPI.TaobaoAPI.setCERTCODE(certcode);
        BS2.BSTaobaoAPI.TaobaoAPI.setLoginPro(username, password);
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return 0;
        int rowCount = Convert.ToInt32(xml.SelectNodes("rsp/totalResults").Item(0).InnerText);
        string[] idds = new string[rowCount];
        int pageno = 1;
        for (int i = 1; i < idds.Length / _PageSize + 1; i++)
        {
            string[] tmp = GetTradeTidList(username, password, appkey, certcode, sessionId, _PageSize, i);
            Array.Copy(tmp, 0, idds, (i - 1) * _PageSize, tmp.Length);
            pageno++;
        }
        if (idds.Length % _PageSize != 0)
        {
            string[] tmp = GetTradeTidList(username, password, appkey, certcode, sessionId, _PageSize, pageno);
            Array.Copy(tmp, 0, idds, (pageno - 1) * _PageSize, idds.Length - (pageno - 1) * _PageSize);
        }
        int myCount = 0;
        //依次获取每个订单的详细信息，然后存入数据库        
        for (int i = 0; i < idds.Length; i++)
        {
            DownTBTrade(username, password, appkey, certcode, sessionId, idds[i]);
            myCount++;
        }
        return myCount;
    }
    #endregion

    #region 由skuId获取sku详细信息
    /// <summary>
    /// 由skuId获取sku详细信息
    /// </summary>
    private BS2.BSTaobaoAPI.BSTaobaoItemSKU GetTBSKU(string username, string appkey, string certcode, string skuId)
    {
        string[,] param = new string[,] { { "nick", username },{"sku_id",skuId}, { "sip_apiname", "taobao.item.sku.get" }, 
                    { "fields", "iid,properties,quantity,price,outer_id,created,modified" }, 
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
        BS2.BSTaobaoAPI.TaobaoAPI.setAPPID(appkey);
        BS2.BSTaobaoAPI.TaobaoAPI.setCERTCODE(certcode);
        XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param);
        if (xml == null||xml.OuterXml.Contains("error_rsp"))
            return null;
        BS2.BSTaobaoAPI.BSTaobaoItemSKU sku = new BS2.BSTaobaoAPI.BSTaobaoItemSKU();
        DataSet ds = new DataSet();
        ds.ReadXml(new XmlNodeReader(xml));
        DataTable dt = ds.Tables["sku"];
        if (dt != null && dt.Rows.Count > 0)
        {
            sku._iid = dt.Rows[0]["iid"].ToString();
            sku._created = dt.Rows[0]["created"].ToString();
            sku._modified = dt.Rows[0]["modified"].ToString();
            sku._price = dt.Rows[0]["price"].ToString();
            sku._properties = dt.Rows[0]["properties"].ToString();
            sku._quantity = dt.Rows[0]["quantity"].ToString();            
        }       
        return sku;
    }
    #endregion

    #region GetTradeTidList
    private string[] GetTradeTidList(string username, string password, string appkey, string certcode, string sessionId, int pagesize, int pageno)
    {        
        string[,] param = new string[,] { { "nick", username }, { "sip_apiname", "taobao.trades.sold.get" }, { "fields", "tid" }, {"page_size",pagesize.ToString()},{"page_no",pageno.ToString()},
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
               
        BS2.BSTaobaoAPI.TaobaoAPI.setAPPID(appkey);       
        BS2.BSTaobaoAPI.TaobaoAPI.setLoginPro(username, password);
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param,username,password,certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return null;
        string[] idds = new string[pagesize];
        for (int i = 0; i < idds.Length; i++)
            idds[i] = xml.SelectNodes("rsp/trade/tid").Item(i) == null ? null : xml.SelectNodes("rsp/trade/tid").Item(i).InnerText;
        return idds;
    }
    #endregion

    #region GetTradeFromXml
    public  BS2.BSTaobaoAPI.BSTaobaoTrade GetTradeFromXml(XmlDocument xml)
    {
        BS2.BSTaobaoAPI.BSTaobaoTrade trade = new BS2.BSTaobaoAPI.BSTaobaoTrade();
        foreach (XmlNode node in xml.SelectSingleNode("rsp/trade").ChildNodes)
        {
            if (node.Name == "seller_nick")
                trade._seller_nick = node.InnerText;
            if (node.Name == "buyer_nick")
                trade._buyer_nick = node.InnerText;
            if (node.Name == "iid")
                trade._iid = node.InnerText;
            if (node.Name == "price")
                trade._price = node.InnerText;
            if (node.Name == "num")
                trade._num = node.InnerText;
            if (node.Name == "created")
                trade._created = node.InnerText;
            if (node.Name == "type")
                trade._type = node.InnerText;
            if (node.Name == "tid")
                trade._tid = node.InnerText;
            if (node.Name == "alipay_no")
                trade._alipay_no = node.InnerText;
            if (node.Name == "payment")
                trade._payment = node.InnerText;
            if (node.Name == "status")
                trade._status = node.InnerText;
        }
        foreach (XmlNode node2 in xml.SelectNodes("rsp/trade/orders/order"))
        {
            BS2.BSTaobaoAPI.BSTaobaoTrade_Order order = new BS2.BSTaobaoAPI.BSTaobaoTrade_Order();
            if (node2.SelectNodes("iid").Item(0) != null)
            {
                order._iid = node2.SelectNodes("iid").Item(0).InnerText;
            }
            if (node2.SelectNodes("sku_id").Item(0) != null)
            {
                order._sku_id = node2.SelectNodes("sku_id").Item(0).InnerText;
            }
            if (node2.SelectNodes("num").Item(0) != null)
            {
                order._num = node2.SelectNodes("num").Item(0).InnerText;
            }
            if (node2.SelectNodes("title").Item(0) != null)
            {
                order._title = node2.SelectNodes("title").Item(0).InnerText;
            }
            if (node2.SelectNodes("price").Item(0) != null)
            {
                order._price = node2.SelectNodes("price").Item(0).InnerText;
            }
            if (node2.SelectNodes("pic_path").Item(0) != null)
            {
                order._pic_path = node2.SelectNodes("pic_path").Item(0).InnerText;
            }
            if (node2.SelectNodes("seller_nick").Item(0) != null)
            {
                order._seller_nick = node2.SelectNodes("seller_nick").Item(0).InnerText;
            }
            if (node2.SelectNodes("buyer_nick").Item(0) != null)
            {
                order._buyer_nick = node2.SelectNodes("buyer_nick").Item(0).InnerText;
            }
            if (node2.SelectNodes("type").Item(0) != null)
            {
                order._type = node2.SelectNodes("type").Item(0).InnerText;
            }
            if (node2.SelectNodes("created").Item(0) != null)
            {
                order._created = node2.SelectNodes("created").Item(0).InnerText;
            }
            if (node2.SelectNodes("refund_status").Item(0) != null)
            {
                order._refund_status = node2.SelectNodes("refund_status").Item(0).InnerText;
            }
            if (node2.SelectNodes("tid").Item(0) != null)
            {
                order._tid = node2.SelectNodes("tid").Item(0).InnerText;
            }
            trade.AddChildBus(order);
        }
        return trade;
    }
    #endregion

    #region 下载一条订单信息并插入数据库

    /// <summary>
    /// 下载一条订单信息并插入数据库

    /// </summary>   
    public int DownTBTrade(string username, string password, string appkey, string certcode, string sessionId, string tid)
    {
        string fields = "iid,seller_nick,buyer_nick,tid,created,num,payment,price,alipay_no,status,type,orders";
        string[,] param = new string[,] { { "tid", tid }, {"nick",username},{ "sip_apiname", "taobao.trade.get" }, { "fields", fields }, 
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = null;
        xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param, username, password, certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return 800001 ;//下载淘宝数据失败
        //InsertIntoTB(xml);
        //插入B2C 表orderdoc,orderdetail
        return  InsertIntoOrder(xml,username,password,appkey,certcode,sessionId);
    }
   
    /// <summary>
    /// 下载一条订单信息并插入数据库


    /// </summary>   
    public int DownTBTrade(BS2.BSTaobaoAPI.BSTaobaoBussinessList slist, string username, string password, string appkey, string certcode, string sessionId, string tid)
    {
        string fields = "iid,seller_nick,buyer_nick,tid,created,num,payment,price,alipay_no,status,type,orders";
        string[,] param = new string[,] { { "tid", tid }, {"nick",username},{ "sip_apiname", "taobao.trade.get" }, { "fields", fields }, 
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = null;
        xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param, username, password, certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return 800001;//下载淘宝数据失败
        //InsertIntoTB(xml);
        //插入B2C 表orderdoc,orderdetail
        //if (slist.Count < 1)
        //  return 800001;//下载淘宝数据失败
        return InsertIntoOrder(xml, username, password, appkey, certcode, sessionId);
    }
    #endregion

    #region 订单存入本地数据库

    #region 判断订单是否已经下载过


    /// <summary>
    /// 判断订单是否存在
    /// </summary> 
    bool CheckTidisExist(string tid, string username)
    {
        try
        {
            string ddly = null;
            string sql = "select ddly from tb_shangdian where tbzh='" + username + "'";
            DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
            ddly = ds.Tables[0].Rows[0][0].ToString();
            sql = "select count(*) from orderdoc where byzd18='" + tid + "' and order_ofcode='" + ddly + "'";
            if (DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql) > 0)
                return true;
        }
        catch
        {
        }
        return false;
    }
    #endregion
    int InsertIntoOrder(XmlDocument xml, string username, string password, string appkey, string certcode, string sessionId)
    {
        List<Model.BUYPOCKETDETAIL> buyList = new List<Model.BUYPOCKETDETAIL>();
        List<Model.PAYDETAIL> payList = new List<Model.PAYDETAIL>();
        Model.ORDERDOC orderDoc = new Model.ORDERDOC();
        //订单
        BS2.BSTaobaoAPI.BSTaobaoTrade myTrade = GetTradeFromXml(xml);
        //foreach (BS2.BSTaobaoAPI.BSTaobaoBussiness _cur in slist)
        //{
        //    BS2.BSTaobaoAPI.BSTaobaoTrade _tt = (BS2.BSTaobaoAPI.BSTaobaoTrade)_cur;
        //    if (_tt._tid == tid)
        //    {
        //        myTrade = (BS2.BSTaobaoAPI.BSTaobaoTrade)_cur;
        //    }
        //}
        if (myTrade == null)
            return 800001;//下载淘宝数据失败
        //orderDoc.ORDER_ID = myTrade._tid;
        string tid = myTrade._tid;//淘宝交易号


        string sqlstring = "select * from tb_appcode where field1 is  not null and field2 = '" + username + "'";//根据淘宝用户名查询淘宝网AppKey,SessionKey,AppSecret
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sqlstring);

        SortedList<string, string> parameters = new SortedList<string, string>();
        parameters.Add("nick", username);
        parameters.Add("method", "taobao.trade.fullinfo.get");
        //交易号   收货人      省份            城市            地区            详细地址        邮编            电话            手机
        parameters.Add("fields", "tid,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_phone,receiver_mobile");
        parameters.Add("tid", tid);
        parameters.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        parameters.Add("format", "xml");
        parameters.Add("app_key", ds.Tables[0].Rows[0]["appkey"].ToString());
        parameters.Add("session", ds.Tables[0].Rows[0]["field1"].ToString());
        parameters.Add("v", "1.0");

        XmlDocument document = this.GetInterfaceToDocument(parameters, ds.Tables[0].Rows[0]["appcertcode"].ToString());



        if (!CheckTidisExist(tid, username))
        {
            orderDoc.BYZD18 = tid;//淘宝交易号




            orderDoc.ORDER_CUSTOMERCODE = myTrade._buyer_nick;//客户代码，是买家.
            orderDoc.ORDER_OFCODE = GetOrderofCodebyTbZh(myTrade._seller_nick);//订单来源//订单来源
            orderDoc.ORDER_TRANCOST = 0; //物流费用
            orderDoc.ORDER_QTY = 0;  //总数量 构造订单商品明细时重写
            orderDoc.ORDER_AMT = 0; //金额 构造订单商品明细时重写
            orderDoc.ORDER_DISC = Convert.ToDecimal(1);//折扣 会员注册成功后重写



            orderDoc.ORDER_TAMT = 0;//构造订单商品明细结束重写 总金额




            orderDoc.ORDER_OFFERAMT = Convert.ToDecimal(0);//让利金额
            orderDoc.ORDER_AAMT = orderDoc.ORDER_TAMT - orderDoc.ORDER_OFFERAMT;//实际金额=总金额-让利金额   构造订单商品明细结束时重写
            orderDoc.ORDER_CREATER = "admin";
            orderDoc.ORDER_CREATEDATE = Convert.ToDateTime(myTrade._created);
            orderDoc.ORDER_WEIGHT = Convert.ToDecimal(0); //构造订单商品明细时重写
            //收货人信息(物流数据)
            BS2.BSTaobaoAPI.BSTaobaoShipping shipping = new TB_Shipping().GetTBShipping(username, password, appkey, certcode, sessionId, myTrade._tid);
            if (shipping != null)
            {
                orderDoc.ORDER_GETER = shipping._receiver_name;
                orderDoc.ORDER_TRANERCODE = shipping._company_name;
                orderDoc.ORDER_TRANBILLCODE = shipping._out_sid;
                orderDoc.ORDER_COSTNATURE = shipping._freight_payer == "buyer" ? "002" : "001";
            }

            //订单支付明细
            Model.PAYDETAIL payDetail = new Model.PAYDETAIL();

            payDetail.PD_DETAILID = DateTime.Now.ToFileTime().ToString();
            payDetail.PD_ACCOUNT = GetTBZHbyTbZh(myTrade._seller_nick);
            payDetail.PD_DTCODE = "002";// 淘宝，担保交易




            payDetail.PD_PAYTYPE = GetTBZFFSbyTbZh(myTrade._seller_nick); //支付宝支付



            payDetail.PD_PAYAMT = Convert.ToDecimal(myTrade._payment);
            payDetail.PD_DEALID = myTrade._alipay_no;
            payDetail.PD_PAYDATE = DateTime.Now;
            //需要绑定淘宝支付状态，放在备注中




            payDetail.PD_NOTE = new TBCommon().GetTradeStatus(myTrade._status);

            payList.Add(payDetail);
            //买家信息
            myTrade._buyer_nick = "TB-" + myTrade._buyer_nick;
            string buyer = myTrade._buyer_nick;
            //判断买家是否存在
            string DM;
            if (!CheckBuyerIsExist(buyer))
            {
                Model.ORDERFROM of = new BLL.ORDERFROM().GetModel(orderDoc.ORDER_OFCODE);
                DM = AddBuyer(buyer, of.OF_ACODE); //向系统注册此买家信息
                if (DM.Length < 2)
                    return 800002;         //注册会员失败
            }
            else
            {
                DM = GetGKDMbynick(buyer);
            }
            Model.V_VIPSET vvps = new BLL.V_VIPSET().GetModelByGKDM(DM);
            if (vvps != null)
            {
                orderDoc.ORDER_DISC = vvps.ZK;  //重写订单主表折扣信息
            }

            //商品信息        
            foreach (BS2.BSTaobaoAPI.BSTaobaoTrade_Order order in myTrade.Trade_Order)
            {
                Model.BUYPOCKETDETAIL sp = new Model.BUYPOCKETDETAIL();
                sp.BPD_USERCODE = DM;
                orderDoc.ORDER_CUSTOMERCODE = DM;
                //获取已关联商品的商品代码
                string _spCode = GetSPDMbyiidAndShopId(order._iid, new TBCommon().GetShopIdByZH(username));
                Model.SHANGPIN SHANGPIN = new BLL.SHANGPIN().GetModel(_spCode);
                if (_spCode == null)
                {
                    sp.BPD_COMMCODE = "0";
                }
                else
                {
                    if (_spCode.Length < 1)
                        sp.BPD_COMMCODE = "0";
                    else
                        sp.BPD_COMMCODE = _spCode;//获取商品代码
                }
                ;//获取商品代码
                sp.BPD_NOTE = order._title;//在备注中存储宝贝名称
                sp.BPD_QTY = Convert.ToDecimal(order._num);
                orderDoc.ORDER_QTY += Convert.ToDecimal(order._num); //重写订单主表数量
                if (sp.BPD_COMMCODE == "0")
                {
                    sp.BPD_SPRICE = Convert.ToDecimal(order._price);
                    sp.BPD_DISC = 1;//商品折扣
                }
                else
                {
                    sp.BPD_DISC = Convert.ToDecimal(order._price) / SHANGPIN.BZSJ;
                    sp.BPD_SPRICE = SHANGPIN.BZSJ;
                }

                sp.BPD_APRICE = Convert.ToDecimal(order._price);
                sp.BPD_SAMT = sp.BPD_SPRICE * Convert.ToInt32(order._num);//标准金额
                sp.BPD_AAMT = Convert.ToDecimal(order._price) * Convert.ToInt32(order._num);//实际金额
                orderDoc.ORDER_AMT += sp.BPD_AAMT;  //重写订单主表总金额



                sp.BPD_ADDITG = sp.BPD_AAMT * (new BLL.V_VIPSET().GetBaseBS(DM));
                if (sp.BPD_ADDITG == 0)
                    return 800003;//获取积分倍数失败

                if (_spCode == null)
                {
                    sp.BPD_WEIGHT = 0; //商品重量
                    orderDoc.ORDER_WEIGHT = 0;//重写订单主表总重量                
                }
                else
                {
                    if (_spCode.Length < 1)
                    {
                        sp.BPD_WEIGHT = 0; //商品重量
                        orderDoc.ORDER_WEIGHT = 0;//重写订单主表总重量   
                    }
                    else
                    {
                        Model.COMMODITY_AUTO ca = new BLL.COMMODITY_AUTO().GetModel(_spCode);
                        sp.BPD_WEIGHT = ca.CA_WEIGHT; //商品重量
                        orderDoc.ORDER_WEIGHT += ca.CA_WEIGHT * Convert.ToDecimal(order._num); //重写订单主表总重量



                    }

                }
                sp.BPD_COMMCOLOR = "null";
                sp.BPD_COMMSIZE = "null";
                if (order._sku_id != null)
                {
                    BS2.BSTaobaoAPI.BSTaobaoItemSKU sku = GetTBSKU(username, appkey, certcode, order._sku_id);
                    //sku._properties 222:2333;333:4444
                    List<TBCommon.PropValue> propList = new TBCommon().GetPropValuesbySkuProperty(sku._properties);
                    foreach (TBCommon.PropValue p in propList)
                    {
                        if (p.propCode.Contains("颜色"))
                        {
                            sp.BPD_COMMCOLOR = GetGuiCodebyName(p.propName);    //红色   
                            if (sp.BPD_COMMCOLOR == null)
                                sp.BPD_COMMCOLOR = "null";
                        }
                        if (p.propCode.Contains("尺码"))
                        {
                            sp.BPD_COMMSIZE = GetGui2CodebyName(p.propName);//s
                            if (sp.BPD_COMMSIZE == null)
                                sp.BPD_COMMSIZE = "null";
                        }
                    }
                }
                buyList.Add(sp);
            }
            orderDoc.ORDER_TAMT = orderDoc.ORDER_TRANCOST + orderDoc.ORDER_AMT; //总金额



            orderDoc.ORDER_AAMT = orderDoc.ORDER_TAMT - orderDoc.ORDER_OFFERAMT;//实际金额
            #region 收货信息添加
            foreach (XmlNode node in document.GetElementsByTagName("trade"))
            {
                string dizhi = "(";
                //收货人

                if (node.SelectSingleNode("receiver_name") != null)
                {
                    orderDoc.ORDER_GETER = node.SelectSingleNode("receiver_name").InnerText;
                }
                //省份
                if (node.SelectSingleNode("receiver_state") != null)
                {
                    dizhi += node.SelectSingleNode("receiver_state").InnerText + " ";
                    string sql = "select ProId from Province where proname like '" + node.SelectSingleNode("receiver_state").InnerText + "%'";//查询省份编号
                    DataSet result = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
                    if (result.Tables[0].Rows.Count != 0)//判集合是否为空

                    {
                        orderDoc.ORDER_PROVINCE = result.Tables[0].Rows[0][0].ToString();
                    }
                }
                //城市
                if (node.SelectSingleNode("receiver_city") != null)
                {
                    dizhi += node.SelectSingleNode("receiver_city").InnerText + " ";
                    string sql = "select CityId from City where cityname = '" + node.SelectSingleNode("receiver_city").InnerText + "'";//查询市区编号
                    DataSet result = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
                    if (result.Tables[0].Rows.Count != 0)//判集合是否为空

                    {
                        orderDoc.ORDER_CITY = result.Tables[0].Rows[0][0].ToString();
                    }
                }
                //地区
                if (node.SelectSingleNode("receiver_district") != null)
                {
                    dizhi += node.SelectSingleNode("receiver_district").InnerText;
                    string sql = "select areaid from Area where areaname = '" + node.SelectSingleNode("receiver_district").InnerText + "' and cityid = " + Convert.ToInt32(orderDoc.ORDER_CITY);//查询区县编号
                    DataSet result = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
                    if (result.Tables[0].Rows.Count != 0)//判集合是否为空

                    {
                        orderDoc.ORDER_AREA = result.Tables[0].Rows[0][0].ToString();
                    }
                }
                //详细地址
                if (node.SelectSingleNode("receiver_address") != null)
                {
                    orderDoc.ORDER_GETADDRESS = node.SelectSingleNode("receiver_address").InnerText + dizhi + ")";
                }
                //邮编
                if (node.SelectSingleNode("receiver_zip") != null)
                {
                    orderDoc.ORDER_GETPOSTCODE = node.SelectSingleNode("receiver_zip").InnerText;
                }
                //电话
                if (node.SelectSingleNode("receiver_phone") != null)
                {
                    orderDoc.ORDER_GETERPHONE1 = node.SelectSingleNode("receiver_phone").InnerText;
                }
                //手机
                if (node.SelectSingleNode("receiver_mobile") != null)
                {
                    orderDoc.ORDER_GETERPHONE2 = node.SelectSingleNode("receiver_mobile").InnerText;
                }
            }
            #endregion
            if (new BLL.ORDERDOC().Order_Insert_HouTai(orderDoc, buyList, payList, 1) == "")
                return 800004;//订单插入数据库失败




            return 0;
        }
        return 0;
    }

    #endregion

    #region 由颜色名称获取代码

    /// <summary>
    /// 由颜色名称获取代码

    /// </summary> 
    string GetGuiCodebyName(string colorName)
    {
        string sql = "select field1 from tb_guige1 where tb_mc='" + colorName + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return colorName;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    #endregion

    #region 由尺码名称获取尺码代码

    /// <summary>
    /// 由尺码名称获取尺码代码

    /// </summary>
    string GetGui2CodebyName(string sizeName)
    {
        string sql = "select field1 from tb_guige2 where tb_mc='" + sizeName + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return sizeName;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    #endregion

    #region 根据商品的GUID和店铺ID取商品代码

    /// <summary>
    /// 由iid和店铺id获取商品代码
    /// </summary>
    string GetSPDMbyiidAndShopId(string iid, int shopid)
    {
        string sql = "select field2 from tb_baobei where pid=" + shopid + " and field1='" + iid + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    #endregion

    #region 判断买家是否存在
    /// <summary>
    /// 判断买家是否存在
    /// </summary>
    bool CheckBuyerIsExist(string nick)
    {
        string sql = "select count(*) from v_customer where byzd5='" + nick + "'";
        if (DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql) > 0)
            return true;      
        return false;
    }
    #endregion

    #region 根据昵称取得用户账号
    string GetGKDMbynick(string nick)
    {
        string sql = "select dm from v_customer where byzd5='" + nick + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    #endregion

    #region 向系统注册买家

    //向系统注册买家

    /// <summary>
    /// 
    /// </summary>
    /// <param name="nick">昵称</param>
    /// <param name="df">标志符</param>
    /// <returns></returns>
    string AddBuyer(string nick,string df)
    {
        string result = RegERP(nick, df);
        while (result == "1")
        {
            result = RegERP(nick, df);
        }
        return result;
    }
    string RegERP(string nick, string df)
    {
        try
        {
            string key = System.Configuration.ConfigurationSettings.AppSettings["CODE"].ToString();
            string sddm = System.Configuration.ConfigurationSettings.AppSettings["ckdm"].ToString();
            string accounts = nick;
            string sex = "男";
            string pwd = "000000";
            if (new BLL.SYSPARAM().GetAutoCreateAccountPasswordConfig())
                pwd = "000000";
            string email = "";
            string userName = nick;
            string province = "";
            string city = "";
            string area = "";
            string address = "";
            string postCode = "";
            string mobile = "";
            string phone = "";
            string Nike = nick;
            string source = df;
            string date = DateTime.Now.ToString();
            date = date.Replace("-", "").Replace(" ", "").Replace(":", "");
            accounts = source + date;

            LX_Manage.ERP.Service erp = new LX_Manage.ERP.Service();
            string ReCommendCustomer = "";
            string result = erp.Customer_Add(key, sddm, accounts, userName, sex, pwd, email, address, postCode, mobile, phone, "127.0.0.1", ReCommendCustomer, Nike, province, city, area);
            if (result == "1" || result == "2" || result == "3")
            {
                return result;
            }
            if (result != "-2" && result != "-1" && result != "0" && result != accounts)
            {
                return accounts;
            }
            return result;
        }
        catch
        {
            return "";
        }      
    }
    #endregion

    #region 订单来源
    //订单来源
    string GetOrderofCodebyTbZh(string zh)
    {
        string sql = "select ddly from tb_shangdian where tbzh='" + zh + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    #endregion
    #region 根据淘宝账号返回对应支付宝账号

    //订单来源
    string GetTBZHbyTbZh(string zh)
    {
        string sql = "select field1 from tb_shangdian where tbzh='" + zh + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    //支付方式
    string GetTBZFFSbyTbZh(string zh)
    {
        string sql = "select field2 from tb_shangdian where tbzh='" + zh + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();
    }
     #endregion
    #region 调用淘宝网接口方法

    /// <summary>
    /// 调用淘宝网接口方法

    /// </summary>
    /// <param name="parameters"></param>
    /// <param name="appsecret"></param>
    /// <returns></returns>
    private XmlDocument GetInterfaceToDocument(SortedList<string, string> parameters, string appsecret)
    {
        //2.3 生成sign,格式: app_secret参数1值1参数2值2,生成md5后转为大写

        StringBuilder sb = new StringBuilder();
        sb.Append(appsecret);
        foreach (KeyValuePair<string, string> item in parameters)
        {
            sb.Append(item.Key + item.Value);
        }
        parameters.Add("sign", FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToUpper());//签名参数

        //3.生成url
        string url = "http://gw.api.taobao.com/router/rest?";//线上环境: http://gw.api.taobao.com/router/rest  测试环境: http://gw.sandbox.taobao.com/router/rest
        StringBuilder query = new StringBuilder();
        foreach (KeyValuePair<string, string> item in parameters)
        {
            query.Append(item.Key + "=" + System.Web.HttpUtility.UrlEncode(item.Value, System.Text.Encoding.UTF8) + "&");
        }
        url += query.ToString().TrimEnd(new char[] { '&' });

        //4.发送获取请求

        WebRequest webRequest = WebRequest.Create(new Uri(url));
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        webRequest.Timeout = 5000;
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(((WebResponse)webRequest.GetResponse()).GetResponseStream());
        return xmlDocument;

    }
    #endregion
}
